package com.tengju.bff.interfaces.manage.crm.user.facade;

import com.beust.jcommander.internal.Lists;
import com.tengju.bff.interfaces.manage.crm.user.assembler.CrmMarketAssembler;
import com.tengju.bff.interfaces.manage.crm.user.vo.*;
import com.tengju.bff.interfaces.shared.AmountType;
import com.tengju.bff.interfaces.shared.AmountVO;
import com.tengju.data.domain.model.clickhouse.OdsMarketIndex;
import com.tengju.data.domain.model.clickhouse.OdsTengjuDataAchievementBounsLogRepository;
import com.tengju.data.domain.model.report.AchievementBonus;
import com.tengju.data.domain.model.report.AchievementBonusRepository;
import com.tengju.data.domain.model.user.UserIdCode;
import com.tengju.data.domain.shared.CastUtil;
import com.tengju.data.domain.shared.Month;
import com.tengju.user.domain.model.user.UserInfoRepository;
import com.tengju.user.domain.service.RemoteUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 李大仙
 * @Date: 2021/4/1 9:03 下午
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class CrmMarketFacade {

    private final AchievementBonusRepository achievementBonusRepository;
    private final OdsTengjuDataAchievementBounsLogRepository odsTengjuDataAchievementBounsLogRepository;

    public MonthMarketAnalysisVO typeAnalysis(UserIdCode idCode, Integer month) {
        MonthMarketAnalysisVO monthMarketAnalysisVO = new MonthMarketAnalysisVO();
        LocalDate monthDate = LocalDate.parse(month + "01", DateTimeFormatter.ofPattern("yyyyMMdd"));
        List<AchievementBonus> bonusList = achievementBonusRepository.find(monthDate, idCode);
        if (CollectionUtils.isEmpty(bonusList)) {
            return monthMarketAnalysisVO;
        }
        BigDecimal totalAchievement = BigDecimal.ZERO;
        BigDecimal totalBonus = BigDecimal.ZERO;
        List<MarketTypeVO> typeAnalysis = new ArrayList<>();
        for (AchievementBonus bonus : bonusList) {
            totalAchievement = totalAchievement.add(bonus.getAchievement());
            totalBonus = totalBonus.add(bonus.getProfit());
        }

        BigDecimal finalTotalAchievement = totalAchievement;
        typeAnalysis = bonusList.stream().filter(bonus -> !(bonus.getAchievement() == null || bonus.getAchievement().compareTo(BigDecimal.valueOf(100)) < 0))
                .map(bonus -> CrmMarketAssembler.bonusToTypeVO(bonus, finalTotalAchievement)).collect(Collectors.toList());

        typeAnalysis = typeAnalysis.stream().sorted(Comparator.comparingDouble(v -> CastUtil.castDouble(CastUtil.castString(v.getMarketIndex().getAmount()))))
                .collect(Collectors.toList());
        Collections.reverse(typeAnalysis);

        monthMarketAnalysisVO.setMarketIndex(new AmountVO(AmountType.INDEX, totalAchievement));
        monthMarketAnalysisVO.setAdIndex(new AmountVO(AmountType.INDEX, totalBonus));
        monthMarketAnalysisVO.setTypeAnalysis(typeAnalysis);
        return monthMarketAnalysisVO;
    }

    public PageMarketRateVO rateAnalysis(CrmMarketAnalysisMarketRateQueryForm form) {
        PageMarketRateVO vo = new PageMarketRateVO();
        vo.setPageSize(form.getPageSize());
        vo.setPageIndex(form.getPageIndex());
        vo.setTotal(0);
        vo.setMarketRateVOS(Lists.newArrayList());

        Integer month = form.getMonth();
        UserIdCode idCode = new UserIdCode(form.getIdCode());

        LocalDate monthDate = LocalDate.parse(month + "01", DateTimeFormatter.ofPattern("yyyyMMdd"));
        List<AchievementBonus> bonusList = achievementBonusRepository.find(monthDate, idCode);
        if (CollectionUtils.isEmpty(bonusList) || month < Month.TENGJU_FIRST_MONTH) {
            return vo;
        }
        int total = odsTengjuDataAchievementBounsLogRepository.selectMarketIndexCount(idCode, month);
        vo.setTotal(total);
        List<OdsMarketIndex> odsMarketIndexList = Lists.newArrayList();
        BigDecimal totalAchievement = BigDecimal.ZERO;
        if (form.getOffset() <= total) {
            odsMarketIndexList = odsTengjuDataAchievementBounsLogRepository.selectMarketIndexPage(idCode, month,form.getOffset(),form.getPageSize());
            totalAchievement = odsTengjuDataAchievementBounsLogRepository.getMarketIndexAchievementTotal(idCode, month);
        }
        if (CollectionUtils.isEmpty(odsMarketIndexList)) {
            return vo;
        }
        BigDecimal finalTotalAchievement = totalAchievement;
        List<MarketRateVO> list = odsMarketIndexList.stream()
                .map(o -> CrmMarketAssembler.assemblerToRateVO(o, finalTotalAchievement))
                .collect(Collectors.toList());
        vo.setMarketRateVOS(list);
        return vo;
    }
}
